{% extends "base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% block head_title %}{% trans "Pré-inscription sans engagement" %}{% endblock %}

{% block bootstrap3_extra_script %}

  {% include 'snippets/datetimepicker_js.html' %}

  <script type="text/javascript">
    /**
     * Mark row as "to delete", disable modify/accept.
     */
    function deleteRow(event) {
      event.preventDefault();
      event.stopPropagation();
      const $line = $(event.target).closest("tr");
      const isDeletedState = $(".delete-hidden-field", $line).val() === "on";

      // Deleted state fields
      $(".delete-hidden-field", $line).val(isDeletedState ? "" : "on");
      $line.toggleClass("danger");

      // Deleted state actions
      $(".delete-button .glyphicon", $line).toggleClass("glyphicon-delete").toggleClass("glyphicon-repeat");
      $(".modify-button, .accept-button", $line).toggleClass("hidden");
    }

    /**
     * Make row editable. Disable delete/accept.
     */
    function modify(event) {
      event.preventDefault();
      event.stopPropagation();
      const $line = $(event.target).closest("tr");
      const $select = $("select", $line);
      // Trick for readonly select with a sibling hidden field https://stackoverflow.com/questions/368813
      const $hiddenSelect = $select.closest("td").find("input[type=hidden]");
      const formRegex = RegExp(/form-(\d*)-/g);
      const prefix = $("input", $line)[0].name.match(formRegex)[0];
      const $datepicker = $(`#id_${prefix}date_pickers`, $line);
      const isModifyState = !$("input", $line).prop("readonly");

      // (Dis)Allow to modify fields
      $("input", $line).prop("readonly", isModifyState);
      $select.prop("disabled", isModifyState);
      $hiddenSelect.prop("disabled", !isModifyState);
      if (isModifyState) {
        $hiddenSelect.val($select.val());
      } else {
        $datepicker.datetimepicker({"format": "DD.MM.YYYY"});
      }

      // Modify state actions
      $(".modify-button .glyphicon", $line).toggleClass("glyphicon-pencil").toggleClass("glyphicon-repeat");
      $(".delete-button, .accept-button", $line).toggleClass("hidden");
    }

    /**
     * Mark row accepted. Disable modify/delete.
     */
    function accept(event) {
      event.preventDefault();
      event.stopPropagation();
      const $line = $(event.target).closest("tr");
      const formRegex = RegExp(/form-(\d*)-/g);
      const prefix = $("input", $line)[0].name.match(formRegex)[0];
      const isAcceptedState = $(`[name=${prefix}is_validated]`, $line).val() === "true";

      // Accepted state fields
      $(`[name=${prefix}is_validated]`, $line).val(String(!isAcceptedState));
      $line.toggleClass("success");

      // Accepted state actions
      $(".accept-button .glyphicon", $line).toggleClass("glyphicon-ok").toggleClass("glyphicon-repeat");
      $(".delete-button, .modify-button", $line).toggleClass("hidden");
    }

    function initialState(line) {
      const formRegex = RegExp(/form-(\d*)-/g);
      const prefix = $("input", line)[0].name.match(formRegex)[0];
      const isAcceptedState = $(`[name=${prefix}is_validated]`, line).val() === "true";

      if (isAcceptedState) {
        $(line).toggleClass("success");
        $(".accept-button .glyphicon", line).toggleClass("glyphicon-ok").toggleClass("glyphicon-repeat");
        $(".delete-button, .modify-button", line).toggleClass("hidden");
      }
    }

    /**
     * Add event listeners on document ready.
     */
    $(function() {
      $(".delete-button").on("click", deleteRow);
      $(".modify-button").on("click", modify);
      $(".accept-button").on("click", accept);

      $(".registration-form").each(function(){
        initialState(this);
      });
    });

  </script>

{% endblock %}

{% block content %}
  <h1>{% trans "Inscriptions à valider" %}</h1>


  {% for organization, formset in organizations %}

    <div class="panel panel-default form-inline">
      <div class="panel-heading">
          <p class="panel-title">{% blocktrans with organization=organization %}Établissement : {{ organization }}{% endblocktrans %}</p>
        <p>{% blocktrans with full_name=organization.coordinator.get_full_name %}Coordina·teur·trice : {{ full_name }}{% endblocktrans %}</p>
      </div>

      <div class="panel-body alert-warning">
        {% blocktrans trimmed %}
          Pour confirmer les pré-inscriptions de l'établissement, vous devez donner un statut
          (<strong>supprimé</strong> ou <strong>accepté</strong>) à <strong>toutes</strong> les sessions de la liste.
        {% endblocktrans %}
      </div>


      {% bootstrap_formset_errors formset %}
      <form id="form-container" method="POST" action="" class="">
        {% csrf_token %}

        <input type="hidden" name="form-organization-id" value="{{ organization.id }}">
        {{ formset.management_form }}

        <table class="panel-body form-inline table table-striped">
          <tr>
            <th>{% trans 'Date' %}</th>
            <th>{% trans 'Moment de la journée' %}</th>
            <th>{% trans 'Nombre de classes' %}</th>
            <th>{% trans 'Actions' %}</th>
          </tr>

          {% for form in formset %}

            {% if form.non_field_errors %}
              <tr>
                <td colspan="4" class="alert alert-danger">
                  {% for error in form.non_field_errors %}
                    {{ error }}{% if not forloop.last %}<br>{% endif %}
                  {% endfor %}
                </td>
              </tr>
            {% endif %}

            {% if form.errors.is_validated %}
              <tr>
                <td colspan="4" class="alert alert-danger">
                  {{ form.errors.is_validated.0 }}
                </td>
              </tr>
            {% endif %}

            <tr class="registration-form">
              <td class="form-group-sm">
                {% bootstrap_field form.date size='small' field_class='' show_label=False %}
              </td>
              <td class="form-group-sm">
                {% bootstrap_field form.day_time size='small' field_class='' show_label=False %}
                <input type="hidden" name="{{ form.prefix}}-{{ form.day_time.name }}" value="{{ form.day_time.value }}">
              </td>
              <td class="form-group-sm">
                {% bootstrap_field form.classes_amount size='small' field_class='' show_label=False %}
              </td>

              <td class="row actions">
                <div class="col-md-4">
                  <button class="btn btn-warning btn-sm modify-button" href="#">
                    <span class="glyphicon glyphicon-pencil" aria-hidden="true" title="{% trans 'Modifier' %}"></span>
                  </button>
                </div>
                <div class="col-md-4">
                  <button class="btn btn-danger btn-sm delete-button" href="#">
                    <span class="glyphicon glyphicon-trash" aria-hidden="true" title="{% trans 'Supprimer' %}"></span>
                  </button>
                </div>
                <div class="col-md-4">
                  <button class="btn btn-success btn-sm accept-button" href="#">
                    <span class="glyphicon glyphicon-ok" aria-hidden="true" title="{% trans 'Accepter' %}"></span>
                  </button>
                </div>
                <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ form.instance.id }}">
                <input type="hidden" class="delete-hidden-field" name="form-{{ forloop.counter0 }}-DELETE" value="">
                {% bootstrap_field form.is_validated %}
              </td>
            </tr>
          {% endfor %}

        </table>

        <div class="panel-confirm">
          <button type="submit" class="btn btn-primary pull-right">{% trans "Confirmer" %}</button>
        </div>
      </form>

    </div>
  {% empty %}
    <div class="panel panel-default">
      <div class="panel-heading">
        <p class="panel-title">{% trans 'Validation des pré-inscriptions' %}</p>
      </div>
      <div class="panel-body">
        {% blocktrans trimmed %}
          Il n'y a actuellement aucune pré-inscription à valider pour les cantons que vous gérez.
        {% endblocktrans %}
      </div>
    </div>
  {% endfor %}

{% endblock %}
